import {CanActivate, ExecutionContext, Injectable} from "@nestjs/common";
import {Observable} from "rxjs";
import {Reflector} from "@nestjs/core";
import {RoleEnum} from "../../common/enum/RoleEnum";
import {ROlES_KEY} from "./GlobalGuardProvider";
import config from "../../config";

/**
 * 权限守卫
 */
@Injectable()
export class RoleGuard implements CanActivate{
    constructor(private reflector:Reflector) {
    }

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        const requiredRoles = this.reflector.getAllAndOverride<RoleEnum[]>(ROlES_KEY, [
            context.getHandler(),
            context.getClass()
        ]);
        if (config.localDebug) {
            console.log("本地调试，鉴权放行...");
            return true;
        }
        if (!requiredRoles) {
            return true;
        }
        const { user } = context.switchToHttp().getRequest();
        // 管理员直接放行
        if (user?.roles?.includes(RoleEnum.ADMIN.code)) {
            return true;
        }

        return requiredRoles.some((role) => user?.roles?.includes(role.code));
    }


}
